import Vue from 'vue'
import Vuex from 'vuex'
import $api from "../config/api";

console.log('Vuex',Vuex)
Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		userInfo: uni.getStorageSync('userInfo') || {
		},
		token: uni.getStorageSync('token') || '',
	},
	getters: {
		userInfo: state => state.userInfo,
		token: state => state.token,
	},
	mutations: {
		SET_USERINFO(state, userInfo) {
			uni.setStorageSync('userInfo', userInfo)
			state.userInfo = userInfo
		},
		SET_TOKEN(state, token) {
			uni.setStorageSync('token', token)
			state.token = token
		},
		LOGOUT(state) {
			state.userInfo = {}
			state.token = ''
			uni.removeStorageSync('userInfo')
			uni.removeStorageSync('token')
		}
	},
	actions: {
		getUserInfo({ commit, state }) {
			return new Promise((resolve, reject) => {
				if (!state.userInfo.id) {
					uni.showLoading()
					$api.getUserInfo(18).then(res => {
						uni.hideLoading()
						if (res) {
							commit('SET_USERINFO', res)
							resolve(res)
						} else {
							reject()
						}
					}).finally(() => {
						uni.hideLoading()
					})
				} else {
					reject()
				}
			})
		},
		setUserInfo({ commit, state }, userInfo) {
			uni.showLoading()
			$api.updateUser(state.userInfo.id, {
				nickname: userInfo.nickname,
				avatar_url: userInfo.avatar_url,
				phone: userInfo.phone
			}).then(res => {
				commit('SET_USERINFO', userInfo)
			}).finally(() => {
				uni.hideLoading()
			})
		},
	}
})

export default store
